import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private JFrame frame;
    private JTextField regexField;
    private JLabel imageLabel;
    private String regex = "";
    private String tempFilePath = "temp.txt"; // 临时存储输入的正则
    private String nfaImagePath = "D:\\bianyi\\Regex2\\result\\nfa_graph.png"; // NFA 图像路径
    private String dfaImagePath = "D:\\bianyi\\Regex2\\result\\dfa_graph.png"; // DFA 图像路径

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Main().createAndShowGUI());
    }

    private void createAndShowGUI() {
        // 创建主窗口
        frame = new JFrame("Regex to NFA & DFA Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLayout(new BorderLayout());

        // 顶部状态栏
        JPanel topPanel = new JPanel(new BorderLayout());
        JLabel projectLabel = new JLabel("Regex to Automata");

        JButton fileButton = new JButton("选择文件");
        fileButton.addActionListener(e -> chooseFile());

        topPanel.add(projectLabel, BorderLayout.WEST);
        topPanel.add(fileButton, BorderLayout.EAST);

        // 左侧面板 (输入框 + 按钮)
        JPanel leftPanel = new JPanel(new BorderLayout());

        regexField = new JTextField();
        leftPanel.add(regexField, BorderLayout.NORTH);

        JPanel inputPanel = new JPanel();
        JButton confirmButton = new JButton("确认输入");
        confirmButton.addActionListener(e -> saveRegexToFile());

        inputPanel.add(confirmButton);
        leftPanel.add(inputPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton nfaButton = new JButton("Create NFA");
        JButton dfaButton = new JButton("Create DFA");

        nfaButton.addActionListener(e -> generateNFA());
        dfaButton.addActionListener(e -> generateDFA());

        buttonPanel.add(nfaButton);
        buttonPanel.add(dfaButton);
        leftPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 右侧面板 (显示图像)
        JPanel rightPanel = new JPanel(new BorderLayout());
        imageLabel = new JLabel("Graph will be displayed here", SwingConstants.CENTER);
        rightPanel.add(imageLabel, BorderLayout.CENTER);

        // 组合窗口
        frame.add(topPanel, BorderLayout.NORTH);
        frame.add(leftPanel, BorderLayout.WEST);
        frame.add(rightPanel, BorderLayout.CENTER);

        frame.setVisible(true);
    }

    /** 选择文件并加载正则 */
    private void chooseFile() {
        JFileChooser fileChooser = new JFileChooser();
        int returnValue = fileChooser.showOpenDialog(frame);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            loadRegexFromFile(selectedFile.getAbsolutePath());
        }
    }

    /** 读取文件中的正则 */
    private void loadRegexFromFile(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            regex = reader.readLine();
            regexField.setText(regex);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "文件读取失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** 存储用户输入的正则 */
    private void saveRegexToFile() {
        regex = regexField.getText().trim();
        if (regex.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "请输入正则表达式！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            writer.write(regex);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "无法写入临时文件！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** 生成 NFA */
    private void generateNFA() {
        regex = regexField.getText().trim(); // 确保获取最新的正则
        if (regex.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "请先输入正则！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 调用 NFA 生成逻辑
        String processedRegex = RegularExpressionParser.addJoinSymbol(regex);
        String postfixExpression = new InfixToPostfix(processedRegex).getResult();
        Elem nfaElem = RegularExpressionParser.expressToNFA(postfixExpression);
        RegularExpressionParser.generateDotFileNFA(nfaElem);

        updateImage(nfaImagePath);
    }

    /** 生成 DFA */
    private void generateDFA() {
        regex = regexField.getText().trim(); // 确保获取最新的正则
        if (regex.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "请先输入正则！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 调用 DFA 生成逻辑
        String processedRegex = RegularExpressionParser.addJoinSymbol(regex);
        String postfixExpression = new InfixToPostfix(processedRegex).getResult();
        Elem nfaElem = RegularExpressionParser.expressToNFA(postfixExpression);

        List<DFAState> dfaStates = new ArrayList<>();
        List<DFATransition> dfaTransitions = new ArrayList<>();
        NFAtoDFAConverter.buildDFAFromNFA(nfaElem, dfaStates, dfaTransitions);
        NFAtoDFAConverter.generateDotFileDFA(dfaStates, dfaTransitions);

        updateImage(dfaImagePath);
    }

    /** 更新图像并确保完整显示 */
    private void updateImage(String imagePath) {
        File imageFile = new File(imagePath);
        if (!imageFile.exists()) {
            JOptionPane.showMessageDialog(frame, "图像文件未找到！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        ImageIcon icon = new ImageIcon(imagePath);
        Image image = icon.getImage().getScaledInstance(500, 400, Image.SCALE_SMOOTH); // 适应窗口大小
        imageLabel.setIcon(new ImageIcon(image));
        imageLabel.setText(""); // 清空文本提示
    }
}
